package com.slibra.common.utils.third;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.type.TypeReference;
import com.slibra.common.config.ApplicationProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class AliSMSUtil {

    private static ApplicationProperties.AliCloud aliCloud;

    public AliSMSUtil(ApplicationProperties applicationProperties) {
        AliSMSUtil.aliCloud = applicationProperties.getAliCloud();
    }

    /**
     * 发送短信
     *
     * @param templateCode 模板代码
     * @param phoneNumber  手机号
     * @param paramMap     变量Map
     */
    public static String sendMsg(String templateCode, String phoneNumber, Map<String, Object> paramMap) {
        String accessKeyId = aliCloud.getAccessKeyId();
        String accessKeySecret = aliCloud.getAccessKeySecret();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", aliCloud.getSignName());
        request.putQueryParameter("TemplateCode", templateCode); // 短信模板code- 根据不同业务场景获取
        String paramValueStr = JsonUtil.toJsonStr(paramMap, "阿里短信参数封装");
        request.putQueryParameter("TemplateParam", paramValueStr); // 模板参数赋值

        CommonResponse response;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            throw new RuntimeException("调用平台发送短信失败");
        }
        Map<String, Object> resultMap = JsonUtil.toEntity(response.getData(), new TypeReference<Map<String, Object>>() {
        }, "短信结果解析");
        if (!"OK".equals(resultMap.get("Code"))) {
            log.error("发送短信通知未成功，返回错误码为{}，错误信息为{}", resultMap.get("Code"), resultMap.get("Message"));
//            throw new BadRequestProblem("调用平台发送短信失败", resultMap.get("Message").toString());
            throw new RuntimeException("调用平台发送短信失败:" + resultMap.get("Message").toString());
        }
        return JsonUtil.toJsonStr(response, "aliMessage response");
    }
}
